﻿/**
* 
* @author Chen
* @version 1.0
*
*/

if (!window.top.ngW8) {
    window.top.ngW8 = {
        $modes: {
            win8: 1,
            web: 0
        }
    };
}
if (!window.top.ngW8.$modes) {
    window.top.ngW8.$modes = {
        win8: 1,
        web: 0
    };
}
if (!window.top.ngW8.$mode) {
    window.top.ngW8.$mode = window.top.ngW8.$modes.web;
}
if (!window.top.ngW8.$components) {
    window.top.ngW8.$components = [];
}
if (!window.top.ngW8.$config) {
    window.top.ngW8.$config = {
        $noCache: true
    };
}
if (!window.top.ngW8.$events) {
    window.top.ngW8.$events = {};
    window.top.ngW8.$eventsHandler = {};
}
if (!window.top.ngW8.$events.$onCreateNewScope) {
    window.top.ngW8.$events.$onCreateNewScope = function (callback) {
        window.top.ngW8.$eventsHandler.$onCreateNewScope = callback;
    };
}
window.top.ngW8.$setRootTemplatePath = function (path) {
    if (!window.top.ngW8.$config) {
        window.top.ngW8.$config = {};
    }
    if (!window.top.ngW8.$config.$loaderCache) {
        window.top.ngW8.$config.$loaderCache = {};
    }
    window.top.ngW8.$config.$loaderPath = path;
};
window.top.ngW8.$setNocache = function (path) {
    if (!window.top.ngW8.$config) {
        window.top.ngW8.$config = {};
    }
    window.top.ngW8.$config.$noCache = path;
};
window.top.ngW8.module = angular.module("ngW8", []);
window.top.ngW8.module.directive("template", [function () {
    return {
        restrict: "A",
        template: function (e, a) {
            return ngW8.$componentsCache[a.template].template;
        },
        replace: true,
        transclude: true,
        link: function (s, e, a) {

            if (ngW8.$componentsCache[a.template].func) {
                ngW8.$componentsCache[a.template].func({
                    $s: s,
                    $e: e,
                    $a: a

                });


            }
        }
    }
}]);
window.top.ngW8.ready = function (callback) {
    ngW8.$readyHandler = callback;
};
window.top.ngW8.$ = function (name) {
    if (!ngW8.$instances) {
        ngW8.$instances = {};
    }
    if (!ngW8.$instances[name]) {
        var p = ["ng", "ngW8"];
        angular.forEach(window.top.ngW8.$injections, function (f) {
            p.push(f);
        });
        ngW8.$instances[name] = angular.injector(p).get(name);
    }
    return ngW8.$instances[name];
};
window.top.ngW8.$getHead = function (txt) {
    var ret = [];
    var tmp = "";
    var iHeader = txt.indexOf("<head>");
    if (iHeader > -1) {
        iHeader += "<head>".length;
        var jHeader = txt.indexOf("</head>", iHeader);
        tmp = txt.substring(iHeader, jHeader);
    }
    return tmp;

};
window.top.ngW8.$getCssList = function (txt) {
    var ret = [];

    while (txt.indexOf("<script ") > -1) {
        txt = txt.replace("<script ", "<div class='ng-unvs-script' ");
        txt = txt.replace("</script>", "</div>");
    }
    while (txt.indexOf("<link ") > -1) {
        txt = txt.replace("<link ", "<br class='ng-unvs-link' ");

    }
    var eles = $("<div>" + txt + "</div>").appendTo("body");
    eles.find(".ng-unvs-link").each(function (index, ele) {
        ret.push($(ele).attr("href"));

    });
    eles.remove();
    return ret;
}
window.top.ngW8.$getScriptList = function (txt) {
    var ret = [];
    while (txt.indexOf("<script ") > -1) {
        txt = txt.replace("<script ", "<div class='ng-unvs-script' ");
        txt = txt.replace("</script>", "</div>");
    }
    while (txt.indexOf("<link ") > -1) {
        txt = txt.replace("<link ", "<br class='ng-unvs-link' ");

    }
    var eles = $("<div>" + txt + "</div>").appendTo("body");
    eles.find(".ng-unvs-script").each(function (index, ele) {
        ret.push($(ele).attr("src"));

    });
    eles.remove();
    return ret;
}
window.top.ngW8.$loadScript = function (list, path, callback, index) {
    if (list.length == 0) {
        callback();
        return;
    }
    if (!index) {
        index = 0;
    }
    else {
        if (index == list.length) {
            callback();
            return;
        }
    }
    if (window.top.ngW8.$mode == window.top.ngW8.$modes.web) {
        $.getScript(path + list[index], function (data, textStatus, jqxhr) {
            window.top.ngW8.$loadScript(list, path, callback, index + 1);
        });
    }
    else {
        $.ajax({
            type: "GET",
            url: path + list[index],
            success: function (data) {
                var txtScript = '"use strict";' + '"' + path + list[index] + '";' + data;
                Function("", txtScript)();
                window.top.ngW8.$loadScript(list, path, callback, index + 1);
            }
        });
    }
}
window.top.ngW8.$getDir = function (path) {
    var ret = "";
    var items = path.split('/');
    for (var i = 0; i < items.length - 1; i++) {
        ret += items[i] + "/";
    }
    return ret;
}
window.top.ngW8.$dynaDirective = function (config, complete) {
    $.ajax({
        type: "GET",
        url: window.top.ngW8.$components.rootPath + "/" + config.template,
        success: function (txt) {
            var txtHeader = window.top.ngW8.$getHead(txt);
            var relPath = window.top.ngW8.$getDir(window.top.ngW8.$components.rootPath + "/" + config.template);
            var cssList = window.top.ngW8.$getCssList(txtHeader);
            for (var i = 0; i < cssList.length; i++) {
                var css_link = $("<link>", {
                    rel: "stylesheet",
                    type: "text/css",
                    href: relPath + cssList[i]
                });
                css_link.appendTo('head');
            }
            var scriptList = window.top.ngW8.$getScriptList(txtHeader);

            window.top.ngW8.$loadScript(scriptList, relPath, function () {
                var i = txt.indexOf("<body>") + 6;
                var j = txt.indexOf("</body>", i);
                var txtBody = txt.substring(i, j);
                i = txtBody.indexOf("<script>");
                j = txtBody.indexOf("</script>");
                var txtScript = undefined;
                if (i > -1) {
                    j += 9;
                    txtScript = txtBody.substring(i, j);
                }

                txtBody = txtBody.replace(txtScript, "");
                if (txtScript) {
                    txtScript = txtScript.replace("<script>", "").replace("</script>", "");
                }
                while (txtBody.indexOf("\r\n") > -1) {
                    txtBody = txtBody.replace("\r\n", "");
                }
                var i = 0;
                while (((txtBody != "<")) &&
                    (i < txtBody.length)) {
                    i++;
                }
                var j = txtBody.length - 1;
                while (((txtBody != ">")) &&
                    (j > 0)) {
                    j--;
                }


                if ((j != -1) && (i < txtBody.length)) {
                    txtBody = txtBody.substring(i, j + 1);
                }
                txtBody = ngW8.$("$utils$text").$clean("<!-- Visual Studio Browser Link -->", "<!-- End Browser Link -->", txtBody);

                ngW8.$componentsCache[config.restrict + "_" + config.directive] = {
                    template: txtBody

                };
                if (txtScript) {
                    ngW8.$componentsCache[config.restrict + "_" + config.directive].func = Function("$tmp", '"use strict";' + '"' + config.template + '";' + txtScript);
                }
                window.top.ngW8.module.directive(config.directive, function () {
                    return {
                        restrict: config.restrict,
                        template: function (e, a) {
                            return ngW8.$componentsCache[config.restrict + "_" + config.directive].template;
                        },
                        replace: true,
                        transclude: true,
                        link: function (s, e, a) {

                            if (ngW8.$componentsCache[config.restrict + "_" + config.directive].func) {
                                ngW8.$componentsCache[config.restrict + "_" + config.directive].func({
                                    $s: s,
                                    $e: e,
                                    $a: a

                                });


                            }
                        }
                    }
                });
                complete();
            })


        }
    });

};

window.top.ngW8.$regComponent = function (directiveKey, path, complete) {
    $.ajax({
        type: "GET",
        url: path,
        success: function (txt) {

            var i = txt.indexOf("<body>") + 6;
            var j = txt.indexOf("</body>", i);
            var txtBody = txt.substring(i, j);
            i = txtBody.indexOf("<script>");
            j = txtBody.indexOf("</script>");
            var txtScript = undefined;
            if (i > -1) {
                j += 9;
                txtScript = txtBody.substring(i, j);
            }

            txtBody = txtBody.replace(txtScript, "");
            if (txtScript) {
                txtScript = txtScript.replace("<script>", "").replace("</script>", "");
            }
            while (txtBody.indexOf("\r\n") > -1) {
                txtBody = txtBody.replace("\r\n", "");
            }
            var i = 0;
            while (((txtBody != "<")) &&
                (i < txtBody.length)) {
                i++;
            }
            var j = txtBody.length - 1;
            while (((txtBody != ">")) &&
                (j > 0)) {
                j--;
            }


            if ((j != -1) && (i < txtBody.length)) {
                txtBody = txtBody.substring(i, j + 1);
            }

            ngW8.$componentsCache[directiveKey] = {
                template: txtBody

            };
            if (txtScript) {
                ngW8.$componentsCache[directiveKey].func = Function("$tmp", '"use strict";' + '"' + path + '";' + txtScript);
            }

            complete();

        }
    });

};
window.top.ngW8.$boot = function (ele, startPage, $injection, complete, moduleFunction) {
    $injection.push("ngW8");
    if (!moduleFunction) {
        moduleFunction = function () { };
    }
    window.top.ngW8.$injections = $injection;
    var x = angular.module("MyForm", $injection, complete, moduleFunction);
    angular.bootstrap(ele, $injection);
    var scope = angular.element(ele).scope();

    window.top.ngW8.$rootScope = scope.$root;
    window.top.ngW8.$loader = ngW8.$("$loader");
    if (complete) {
        complete(scope);
    }
    if (window.top.ngW8.$readyHandler) {
        window.top.ngW8.$readyHandler();
        window.top.ngW8.$("$page")(startPage)
            .$whenLoad(function (event) {
                var f = event;
            }).$whenComplete(function (event) {

                event.element.appendTo(ele);
            }).$apply(scope);

    }
    else {
        window.top.ngW8.$("$page")(startPage)
            .$whenLoad(function (sender) {

            })
            .$whenError(function (event) {
                if (event.$error) {
                    $(ele).html("Error:" + event.$error.status);
                }
                else {
                    if (event.message) {
                        $(ele).html("Error:" + event.message);
                    }
                }
                throw (event);
            })
            .$whenComplete(function (event) {
                event.element.appendTo(ele);
            }).$apply(scope);
    }
};
window.top.ngW8.start = function (ele, startPage, $injection, complete) {
    window.top.ngW8.$injections = $injection;
    window.top.ngW8.$componentsCache = {};
    var count = 0;
    if (window.top.ngW8.$components.components.length > 0) {
        for (var i = 0; i < window.top.ngW8.$components.components.length; i++) {

            if (angular.isObject(window.top.ngW8.$components.components[i])) {
                window.top.ngW8.$dynaDirective(window.top.ngW8.$components.components[i], function () {
                    count++;
                    if (count == window.top.ngW8.$components.components.length) {

                        window.top.ngW8.$boot(ele, startPage, $injection, complete);
                    }
                });

            }
            else {
                window.top.ngW8.$regComponent(window.top.ngW8.$components.components[i],
                                        window.top.ngW8.$components.rootPath + "/" + ngW8.$components.components[i] + ".html",
                                        function () {
                                            count++;
                                            if (count == ngW8.$components.components.length) {
                                                window.top.ngW8.$boot(ele, startPage, $injection, complete);
                                            }
                                        });
            }
        }
    }
    else {
        window.top.ngW8.$boot(ele, startPage, $injection, complete);
    }

};
